import requests
import time
from bs4 import BeautifulSoup
import datetime
import pymysql

# 请务必安装lxml！！！如果报不上请检查lxml安装问题
# pip3 install bs4
# pip3 install requests
# pip3 install pymysql
# pip3 install lxml

# 从数据库文件中读取数据
def get_info():
    try:
        db = pymysql.connect(host="test", user="teest",
                            passwd="test",
                            db="test",
                            charset='utf8')
        print("connect to mysql server successfully")
    except:
        print("could not connect to mysql server")
    cs1 = db.cursor()
    
    get = "SELECT * FROM user"
    cs1.execute(get)
    username = []
    password = []
    alldata = cs1.fetchall()
    for s in alldata:
        username.append(s[1])
        password.append(s[2])   
    cs1.close()
    sum = len(username)
    return username, password, sum

# 登录，为后续做准备
def login(s,headers,username,password):
    login_url = 'http://yiqing.ctgu.edu.cn/wx/index/loginSubmit.do'
    data = {
        'username':'',
        'password':'',
    }
    data['username'] = username
    data['password'] = password
    r = s.post(url = login_url,headers = headers,data = data )
    r.encoding = 'utf-8'
    return r.text

# 获取要带有data的html
def get_student_info(s,headers):
    student_info_url = 'http://yiqing.ctgu.edu.cn/wx/health/toApply.do'
    r = s.get(url = student_info_url,headers = headers)
    r.encoding = 'utf-8'
    return r.text

# 解析html,获得data数据
def student_info_parse(html):
    # 引用lxml，不然会解析不了报不上
    bs = BeautifulSoup(html,'lxml')
    data = {
        'ttoken': bs.find(attrs={'name':'ttoken'})['value'], #ttoken
        'province': '湖北省', #省
        'city': '宜昌市', #市
        'district': '西陵区', #县
        'adcode': '443000', #邮编

        'longitude': bs.find(attrs={'name':'longitude'})['value'], #经度
        'latitude': bs.find(attrs={'name':'latitude'})['value'], #纬度
        'sfqz': bs.find(attrs={'name':'sfqz'})['value'],
        'sfys': bs.find(attrs={'name':'sfys'})['value'],
        'sfzy': bs.find(attrs={'name':'sfzy'})['value'],
        'sfgl': bs.find(attrs={'name':'sfgl'})['value'],
        'status': bs.find(attrs={'name':'status'})['value'],
        'sfgr': bs.find(attrs={'name':'sfgr'})['value'],
        'szdz': '湖北省 宜昌市 西陵区',
        'sjh': bs.find(attrs={'name':'sjh'})['value'],
        'lxrxm': bs.find(attrs={'name':'lxrxm'})['value'],
        'lxrsjh': bs.find(attrs={'name':'lxrsjh'})['value'],
        'sffr': '否',
        'sffrAm': '否',
        'sffrNoon': '否',
        'sffrPm': '否',
        'sffy': '否',
        'sfgr': '否',
        'qzglsj': '',
        'qzgldd': '',
        'glyy': '',
        'mqzz': '',
        'sffx': '否',
        'qt':'',
    }
    return data

# 向服务器post数据
def sent_info(s,headers,data):
    sent_info_url = 'http://yiqing.ctgu.edu.cn/wx/health/saveApply.do'
    s.post(url = sent_info_url,headers = headers,data = data)

def main():
    username, password, sum = get_info()
    print('-------------------------------------------')
    print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    print('---------------------------')
    print('账号密码读取成功，共',str(sum),'人')
    print('---------------------------\n')
    finished = 0
    try:
        for i in range(sum):
            headers = {       
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.7 Safari/537.36'
            }
            s = requests.Session()
            state = login(s,headers,username[i],password[i])
            print('No.'+str(i)+'  '+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            if state == 'success':
                print('用户',username[i],'登录成功')
            else:
                print('用户',username[i],'密码错误，登录失败\n')
                continue
            html = get_student_info(s,headers)
            time.sleep(0.1)#等待时间
            try:
                data = student_info_parse(html)
                sent_info(s,headers,data)
                print('用户',username[i],'上报成功\n')
            except:
                print('用户',username[i],'今日已上报\n')
            finished += 1
            time.sleep(0.1)#等待时间
    finally:
        text = '应报:'+str(sum)+'   实报:'+str(finished)
        print(text)


if __name__ == "__main__":
    main()
